package com.echo.boot.design.turing.singleton.innerclass;

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/7/26
 * Time: 9:35
 */
public class InnerClassSingleton implements Serializable {

    static final long serialVersionUID = 42L;


    /**
     * 依赖jvm 类加载机制保证 类的唯一性
     * 只有在实际使用的时候,才会触发类的实例化,所以也是一种懒加载的一种形式
     */
    private static class InnerClassHolder {
        private static InnerClassSingleton instance = new InnerClassSingleton();
    }

    private InnerClassSingleton() {
        if (InnerClassHolder.instance != null) {
            throw new RuntimeException("单例不允许多个实例");
        }
    }

    public static InnerClassSingleton getInstance() {
        return InnerClassHolder.instance;
    }

    Object readResolve() throws ObjectStreamException {
        return InnerClassHolder.instance;
    }


}
